package com.mlm.mlmapp.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.Constants;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.activity.layoutmanager.SyGridLayoutManager;
import com.mlm.mlmapp.adapter.view.AQProgressDialog;
import com.mlm.mlmapp.adapter.view.GridMarginDecoration;
import com.mlm.mlmapp.adapter.view.listener.DresserClickListener;
import com.mlm.mlmapp.adapter.view.listener.OnNextPageShouldDownloadListener;
import com.mlm.mlmapp.adapter.view.listener.OnRcvScrollListener;
import com.mlm.mlmapp.animation.RecyclAnimation;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.utils.CommonUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.DimensionRes;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

@EActivity(R.layout.hairdresserlist)
public class HairDresserListActivity extends BaseActivity implements HTTPCons,
        DresserClickListener {

    public static final int DESC = 1;
    public static final int ASC = 2;
    public static final int NORMAL = 0;
    public static final String POST_LIST = "post_list";
    public static final String STUDIO_LIST = "mendian_list";
    public static final String RATING_DESC = "rating_desc";

    private String post_list = "";
    private String studio_list = "";
    private String rating_desc = "";

    private AQuery aq;
    private DresserlistAdapter adapter;
    List<JSONObject> dresserListDataset;
    private int btnStatusPrice;
    private int btnStatusOrder;
    private String currentPrice = "";
    private String currentOrder = "";
    private String dresserName = "";
    @ViewById
    RecyclerView rv_dresser;
    @ViewById
    LinearLayout btn_back;
    @ViewById
    RelativeLayout btn_search;
    @ViewById
    RelativeLayout search_layout;
    @ViewById
    ImageButton iv_search;
    @ViewById
    TextView btnSearch;
    @ViewById
    Button btn_price;
    @ViewById
    Button btn_order;
    @ViewById
    Button btn_dresser_type;
    @ViewById
    EditText etSearch;
    @ViewById
    ImageView ivDeleteText;
    @ColorRes(R.color.red)
    int redText;
    @DimensionRes(R.dimen.recyclerview_sylist_space)
    float recyclerview_sylist_space;
    int mPage = 1;

    @AfterViews
    public void init() {
        btn_back.setVisibility(View.INVISIBLE);
        btn_search.setVisibility(View.VISIBLE);

        btn_dresser.setCompoundDrawablesWithIntrinsicBounds(null,
                getResources().getDrawable(R.drawable.dresserchecked), null,
                null);
        btn_dresser.setTextColor(getResources().getColor(R.color.red));

        String title = getTitle().toString();
        if (!"".equals(title)) {
            ((TextView) this.findViewById(R.id.tv_title)).setText(title);
        }
        etSearch.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // TODO Auto-generated method stub

            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    ivDeleteText.setVisibility(View.GONE);
                } else {
                    ivDeleteText.setVisibility(View.VISIBLE);
                }
            }
        });

        aq = new AQuery(this);
        aq.hardwareAccelerated11();
        dresserListDataset = new ArrayList<>();

        final GridLayoutManager layoutManager = new SyGridLayoutManager(this, 1);
        rv_dresser.setLayoutManager(layoutManager);

        rv_dresser.addItemDecoration(new GridMarginDecoration(this, 0, 0, 0,
                recyclerview_sylist_space));
        rv_dresser.setItemAnimator(new RecyclAnimation());
        OnRcvScrollListener listener = new OnRcvScrollListener() {

            @Override
            public void onBottom() {
                // TODO Auto-generated method stub
                super.onBottom();
                // mSwipeRefreshWidget.setRefreshing(true);
                updateDataset(mPage);
            }

        };
        rv_dresser.setOnScrollListener(listener);
        adapter = new DresserlistAdapter(HairDresserListActivity.this,
                dresserListDataset);
        rv_dresser.setAdapter(adapter);
        // init sylist date
        updateDataset(mPage);

    }

    @OnActivityResult(REQUEST_CODE)
    void onResult(Intent data) {
        if (data != null) {

            this.post_list = data.getStringExtra(POST_LIST);
            this.studio_list = data.getStringExtra(STUDIO_LIST);
//            this.rating_desc = data.getStringExtra(RATING_DESC);
            if (!"".equals(post_list) || !"".equals(studio_list)
                    || !"".equals(rating_desc)) {
                btn_dresser_type.setTextColor(redText);
                btn_dresser_type.setCompoundDrawables(null, null,
                        CommonUtils.setButtonDrawableRight(this,
                                R.drawable.filter_select), null);
            }
            clearDataset();
            updateDataset(mPage);
        }
    }

    @Click
    void ivDeleteText() {
        etSearch.setText("");
    }

    @Click
    void btnSearch() {
//        Toast.makeText(HairDresserListActivity.this, "quxiao", Toast.LENGTH_SHORT).show();
        search_layout.setVisibility(View.GONE);
        clearDataset();
        dresserName ="";
        updateDataset(mPage);
    }

    @Click
    void iv_search() {
        search_layout.setVisibility(View.VISIBLE);
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(HairDresserListActivity.this.INPUT_METHOD_SERVICE);
                    //隐藏键盘
                    imm.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
//                    Toast.makeText(HairDresserListActivity.this, "点击了搜索", Toast.LENGTH_SHORT).show();
                    dresserName = etSearch.getText().toString().trim();
                    clearDataset();
                    updateDataset(mPage);
                    return true;
                }
                return false;
            }
        });
    }

    @Click
    void btn_dresser_type() {
        HairDresserFilterActivity_.intent(this).extra("postIDs", post_list).extra("studioIDs", studio_list).startForResult(REQUEST_CODE);
    }

    /**
     * desc default,arrow up as ASC, down as DESC
     */
    @Click
    void btn_price() {
        switch (btnStatusPrice) {
            case 0:
                btnStatusPrice = 1;
                currentPrice = "DESC";
                btn_price.setCompoundDrawables(null, null, CommonUtils
                        .setButtonDrawableRight(this, R.drawable.arrow_up), null);
                btn_price.setTextColor(redText);
                break;
            case 1:
                btnStatusPrice = 2;
                currentPrice = "ASC";
                btn_price.setCompoundDrawables(null, null, CommonUtils
                        .setButtonDrawableRight(this, R.drawable.arrow_down), null);
                btn_price.setTextColor(redText);
                break;
            case 2:
            default:
                currentPrice = "DESC";
                btnStatusPrice = 1;
                btn_price.setCompoundDrawables(null, null, CommonUtils
                        .setButtonDrawableRight(this, R.drawable.arrow_up), null);
                btn_price.setTextColor(redText);
        }
        clearDataset();
        updateDataset(mPage);
    }

    /**
     * desc default
     */
    @Click
    void btn_order() {

        switch (btnStatusOrder) {
            case 0:
                btnStatusOrder = 1;
                currentOrder = "ASC";
                btn_order.setCompoundDrawables(null, null, CommonUtils
                        .setButtonDrawableRight(this, R.drawable.arrow_up), null);
                btn_order.setTextColor(redText);
                break;
            case 1:
                btnStatusOrder = 2;
                currentOrder = "DESC";
                btn_order.setCompoundDrawables(null, null, CommonUtils
                        .setButtonDrawableRight(this, R.drawable.arrow_down), null);
                btn_order.setTextColor(redText);
                break;
            case 2:
            default:
                currentOrder = "ASC";

                btnStatusOrder = 1;
                btn_order.setCompoundDrawables(null, null, CommonUtils
                        .setButtonDrawableRight(this, R.drawable.arrow_up), null);
                btn_order.setTextColor(redText);
        }
        clearDataset();
        updateDataset(mPage);
    }

    // when change the condition, need clear dataset
    private void clearDataset() {
        mPage = 1;
        this.dresserListDataset.clear();
        adapter.notifyDataSetChanged();
    }

    // values bought starLevel levlId studioId
    void updateDataset(int page) {
        StringBuilder url = new StringBuilder(get_dresser_list_action);
        url.append("?");
        if (!"".equals(currentPrice)) {
            url.append("values=" + currentPrice);
            url.append("&");
        }

        if (!"".equals(currentOrder)) {
            url.append("bought=" + currentOrder);
            url.append("&");
        }

        if (!"".equals(rating_desc)) {
            url.append("starLevel=" + rating_desc);
            url.append("&");
        }

        if (!"".equals(post_list)) {
            url.append("levlId=" + post_list);
            url.append("&");
        }

        if (!"".equals(studio_list)) {
            url.append("studioId=" + studio_list);
            url.append("&");
        }

        if (!"".equals(dresserName)) {
            url.append("stylistName=" + dresserName);
            url.append("&");
        }
        url.append("page=" + page);
        Log.d("sort", "updateDataset: " + url);
        getSylist(url.toString());

    }

    void getSylist(String url) {
        aq.progress(new AQProgressDialog(this)).ajax(url, JSONArray.class, new AjaxCallback<JSONArray>() {

            @Override
            public void callback(String url, JSONArray object, AjaxStatus status) {
                // TODO Auto-generated method stub
                super.callback(url, object, status);
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                if (object != null && object.length() > 0) {
                    for (int i = 0; i < object.length(); i++) {
                        try {
                            dresserListDataset.add(object.getJSONObject(i));
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    adapter.notifyDataSetChanged();
                    mPage++;
                }
            }

        });

    }

    class DresserlistAdapter extends
            Adapter<DresserlistAdapter.DresserViewHolder> {
        private OnNextPageShouldDownloadListener mOnNextPageShouldDownloadListener;
        private Context mContext;
        private DresserClickListener mOnDresserClickListener;
        private String id;
        private List<JSONObject> array;

        public DresserlistAdapter(Context con, List<JSONObject> array) {
            this.mContext = con;
            this.mOnDresserClickListener = (DresserClickListener) con;
            this.array = array;

        }

        @Override
        public int getItemCount() {
            return array.size();
        }

        @Override
        public DresserViewHolder onCreateViewHolder(ViewGroup parent, int arg1) {
            // TODO Auto-generated method stub
            DresserViewHolder holder;
            holder = new DresserViewHolder(LayoutInflater.from(
                    HairDresserListActivity.this).inflate(
                    R.layout.hairdresser_list_item, parent, false));
            return holder;

        }

        @Override
        public void onBindViewHolder(DresserViewHolder holder, int position) {
            // TODO Auto-generated method stub
            if (array.size() <= 0) {
                return;
            }
            JSONObject obj = array.get(position);
            DresserViewHolder hHolder = holder;

            hHolder.tv_name.setText(getJsonString(obj, "name"));
            hHolder.tv_post.setText(getJsonString(obj, "leveName"));
            hHolder.tv_words.setText(getJsonString(obj, "introduce"));
            hHolder.tv_collections.setText(mContext.getString(
                    R.string.txt_collection, getJsonInt(obj, "collected")));
            hHolder.tv_orders.setText(mContext.getString(R.string.txt_order,
                    getJsonInt(obj, "bought")));
            hHolder.tv_price.setText(this.mContext.getString(
                    R.string.txt_price, getJsonInt(obj, "priceMast")));
            // hHolder.ratingBar1.setRating(getJsonInt(obj, "starLevel"));

            aq.id(hHolder.iv_headimg).image(getJsonString(obj, "iconPhotoUrl"),
                    false, true, 200, 0, null, Constants.FADE_IN);
            aq.id(hHolder.photo_one).image(getJsonString(obj, "photoOne"),
                    false, true, 200, 0, null, Constants.FADE_IN);

            aq.id(hHolder.photo_two).image(getJsonString(obj, "photoTwo"),
                    false, true, 200, 0, null, Constants.FADE_IN);

            aq.id(hHolder.photo_three).image(getJsonString(obj, "photoThr"),
                    false, true, 200, 0, null, Constants.FADE_IN);

        }

        // @Override
        // public void onViewAttachedToWindow(DresserViewHolder holder) {
        // // TODO Auto-generated method stub
        // super.onViewAttachedToWindow(holder);
        //
        // getNextByPosition(holder.getPosition());
        // }
        //
        // private int currentPage = 0;
        //
        // private void getNextByPosition(int position) {
        // if (position % coutPerPage == 0) {
        // // page start from 1 instead of 0,need +1,
        // // e.g. @ position 0 should start downloading page 2
        // // @ position 6 should start downloading page 3
        // int page = position / coutPerPage + 1;
        // // if(page<1){
        // // page=1;
        // // }
        // // bigger than current page then need get nextpage
        // if (currentPage < (page + 1)) {
        // currentPage = page + 1;
        // this.mOnNextPageShouldDownloadListener
        // .onNextPageShouldDownload(currentPage);// next page
        // }
        //
        // }
        //
        // }

        public class DresserViewHolder extends RecyclerView.ViewHolder {
            String id;
            ImageView iv_headimg;
            Button iv_appointment;
            ImageView photo_one;
            ImageView photo_two;
            ImageView photo_three;
            TextView tv_style_intro;
            TextView tv_name;
            TextView tv_post;
            TextView tv_words;
            TextView tv_collections;
            TextView tv_orders;
            TextView tv_type;
            TextView tv_price;

            // RatingBar ratingBar1;

            public DresserViewHolder(View itemView) {
                super(itemView);
                this.tv_style_intro = (TextView) itemView
                        .findViewById(R.id.tv_style_intro);
                this.tv_name = (TextView) itemView.findViewById(R.id.tv_name);
                this.tv_post = (TextView) itemView.findViewById(R.id.tv_post);
                this.tv_words = (TextView) itemView.findViewById(R.id.tv_words);
                this.tv_collections = (TextView) itemView
                        .findViewById(R.id.tv_collections);
                this.tv_orders = (TextView) itemView
                        .findViewById(R.id.tv_orders);
                this.tv_type = (TextView) itemView.findViewById(R.id.tv_type);
                this.tv_price = (TextView) itemView.findViewById(R.id.tv_price);
                this.iv_headimg = (ImageView) itemView
                        .findViewById(R.id.iv_headimg);
                this.iv_appointment = (Button) itemView
                        .findViewById(R.id.iv_appointment);

                this.photo_one = (ImageView) itemView
                        .findViewById(R.id.photo_one);
                this.photo_two = (ImageView) itemView
                        .findViewById(R.id.photo_two);
                this.photo_three = (ImageView) itemView
                        .findViewById(R.id.photo_three);
                // this.ratingBar1 = (RatingBar) itemView
                // .findViewById(R.id.ratingBar1);

                iv_headimg.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        mOnDresserClickListener.onDresserClick(CommonUtils
                                .getJsonString(array.get(getPosition()), "id"));
                    }
                });
                this.iv_appointment.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        mOnDresserClickListener.onAppointmentClick(CommonUtils
                                .getJsonString(array.get(getPosition()), "id"));

                    }
                });
            }
        }

    }


    @Override
    public void onAppointmentClick(String id) {
        // TODO Auto-generated method stub
        BookActivity_.intent(this).extra("id", id).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }

    @Override
    public void onDresserClick(String id) {
        // TODO Auto-generated method stub
        HairDresserDetailActivity_.intent(HairDresserListActivity.this)
                .extra("id", id).start();
    }

    @Click
    void btn_home() {
        MainActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }

    @ViewById
    Button btn_dresser;

    @Click
    void btn_dresser() {
        // HairDresserListActivity_.intent(this).start();

    }

    @Click
    void btn_appointment() {
        BookActivity_.intent(this).start();
    }

    @Click
    void btn_style() {
        HairStyleListActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }

    @Click
    void btn_userinfo() {
        UserInfoActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }


    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
        Intent data = new Intent();
        setResult(RESULT_CANCELED, data);
        this.finish();
    }
}
